<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="25%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="所属区域" prop="agentCode">
        <el-select
          v-model="formData.agentCode"
          placeholder="请选择区域"
          @change="showEmployeeList"
        >
          <el-option
            v-for="agent in agentList"
            :key="agent.code"
            :label="agent.name"
            :value="agent.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择员工" prop="systemUserCode">
        <el-select
          v-model="formData.systemUserCode"
          placeholder="请选择员工"
          reserve-keyword
          filterable
        >
          <el-option
            v-for="homeEmployee in homeEmployeeList"
            :key="homeEmployee.systemUserCode"
            :label="homeEmployee.systemUserName + '-' + homeEmployee.phone"
            :value="homeEmployee.systemUserCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="对外昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入对外昵称" />
      </el-form-item>
      <el-form-item label="工作年限" prop="serviceYear">
        <el-input v-model="formData.serviceYear" placeholder="请输入工作年限" />
      </el-form-item>
      <el-form-item label="简介" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="请输入简介" type="textarea" />
      </el-form-item>
      <el-form-item label="服务项目" prop="project">
        <el-select
          v-model="formData.project"
          placeholder="请选择服务项目"
          multiple
          value-key="code"
        >
          <el-option
            v-for="homeProject in homeProjectList"
            :key="homeProject.code"
            :label="homeProject.name"
            :value="homeProject"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有推荐人" prop="hasReference">
        <el-radio-group v-model="formData.hasReference" class="ml-4">
          <el-radio :label="true" size="large">是</el-radio>
          <el-radio :label="false" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="推荐人员工"
        prop="referenceSystemUserCode"
        v-if="showReferenceSystemUserCode"
      >
        <el-select
          v-model="formData.referenceSystemUserCode"
          placeholder="请选择推荐人员工"
          remote
          :remote-method="showHomeEmployeeReferenceList"
          reserve-keyword
          filterable
        >
          <el-option
            v-for="homeEmployeeRef in homeEmployeeReferenceList"
            :key="homeEmployeeRef.systemUserCode"
            :label="homeEmployeeRef.systemUserName + '-' + homeEmployeeRef.phone"
            :value="homeEmployeeRef.systemUserCode"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as HomeEmployeeApi from '@/api/meijia/home/employee'
import * as AgentApi from '@/api/meijia/agent'
import * as AgentEmployeeApi from '@/api/meijia/agent/employee'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as ProjectApi from '@/api/meijia/project'
import * as UserDetailApi from '@/api/system/user'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  agentCode: undefined,
  systemUserCode: undefined,
  nickname: undefined,
  serviceYear: undefined,
  hasReference: true,
  referenceSystemUserCode: undefined,
  hasHomeEmployee: undefined,
  hasStoreEmployee: undefined,
  project: [],
  introduce: undefined
})
const formRules = reactive({
  agentCode: [{ required: true, message: '所属区域编号不能为空', trigger: 'blur' }],
  systemUserCode: [{ required: true, message: '人员编号不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '对外昵称不能为空', trigger: 'blur' }],
  serviceYear: [{ required: true, message: '工作年限不能为空', trigger: 'blur' }],
  hasReference: [{ required: true, message: '是否有推荐人不能为空', trigger: 'blur' }],
  hasStoreEmployee: [{ required: true, message: '是否是门店人员不能为空', trigger: 'blur' }],
  project: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
  introduce: [{ required: true, message: '简介不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const agentEmployee = ref()
const agentList = ref()
const homeProjectList = ref<ProjectApi.ProjectVO>()
const showReferenceSystemUserCode = ref(true)
const homeEmployeeList = ref()
const homeEmployeeReferenceList = ref()
const showAgentList = async () => {
  agentEmployee.value = AgentEmployeeApi.agentEmployeeByCurrentUser()
  if (agentEmployee.value.data) {
    agentList.value = await AgentApi.getByAgentCode({
      agentCode: agentEmployee.value.data.agentCode
    })
  } else {
    agentList.value = await AgentApi.getByAgentCode({})
  }
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  showAgentList()
  showHomeProjectList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await HomeEmployeeApi.getHomeEmployee(id)
      showEmployeeList(formData.value.agentCode)
      showHomeEmployeeReferenceList(formData.value.referenceSystemUserName)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as HomeEmployeeApi.HomeEmployeeVO
    if (formType.value === 'create') {
      await HomeEmployeeApi.createHomeEmployee(data)
      message.success(t('common.createSuccess'))
    } else {
      await HomeEmployeeApi.updateHomeEmployee(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    agentCode: undefined,
    systemUserCode: undefined,
    nickname: undefined,
    serviceYear: undefined,
    hasReference: true,
    referenceSystemUserCode: undefined,
    project: [],
    introduce: undefined
  }
  formRef.value?.resetFields()
  homeProjectList.value = []
  homeEmployeeList.value = []
  homeEmployeeReferenceList.value = []
}
const showHomeProjectList = async () => {
  homeProjectList.value = await ProjectApi.getHomeProject()
}
const showEmployeeList = async (agentCode) => {
  homeEmployeeList.value = await HomeEmployeeApi.getBindableOrdinaryEmployeeList({
    agentCode: agentCode
  })
}
const showHomeEmployeeReferenceList = async (name: String) => {
  if (name) {
    homeEmployeeReferenceList.value = await UserDetailApi.getReferenceUserDetailByUserName(name)
  }
}
watch(
  () => formData.value.hasReference,
  (New, Old) => {
    if (New == false) {
      formData.value.referenceSystemUserCode = undefined
      showReferenceSystemUserCode.value = false
    } else {
      showReferenceSystemUserCode.value = true
    }
  }
)
</script>
<style scoped>
.el-select {
  width: 100%;
}
</style>
